package com.wkm.chainchain.pbft.p2p;

import com.wkm.chainchain.pbft.common.MyThreadPoolExecutor;
import com.wkm.chainchain.pbft.p2p.handler.BlockchainMsgHandler;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

public class BlockchainWebSocketServer extends WebSocketServer {

    public BlockchainWebSocketServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        webSocket.send(webSocket.getLocalSocketAddress().getPort() + "已建立与你的连接");
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        System.out.println(webSocket.getRemoteSocketAddress() + "客户端与服务器断开连接！");
    }

    /**
     * 当前服务端收到客户端发来的消息 对消息进行处理
     *
     * @param webSocket
     * @param msg
     */
    @Override
    public void onMessage(WebSocket webSocket, String msg) {
        //开启线程异步处理消息
        MyThreadPoolExecutor.threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                BlockchainMsgHandler.getInstance().handler(msg);
            }
        });

    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        System.out.println(webSocket.getRemoteSocketAddress() + "客户端链接错误！");
    }

    @Override
    public void onStart() {
        System.out.println("WebSocket Server端启动...");
    }
}
